package com.sduept.nwld.dataserver.controller.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sduept.bigdata.fault.manager.EquipmentOverhualDetailManager;
import com.sduept.bigdata.fault.parser.entity.EquipmentOverhaulDetail;
import com.sduept.bigdata.fault.special.maintenance.manager.MaintenanceLogManager;
import com.sduept.bigdata.fault.special.maintenance.manager.MaintenanceManager;
import com.sduept.bigdata.fault.special.maintenance.manager.MaintenancePersistManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.special.maintenance.model.MaintenanceLog;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStation;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStationBreaker;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.manager.ManagementUnitMaintainManager;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.PrimaryEquipmentLedger;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.LineSegment;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.cim.parse.utils.BeanUtils;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.util.ExcelUtil;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.permission.PermissionSecurityManager;
import com.sduept.permission.UserOperationManager;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.UserOperationLog;
import com.sduept.permission.entity.UserOperationLog.OperationType;
import com.sduept.permission.manager.DepartManager;
import com.sduept.utils.DateUtil;
import com.sduept.utils.PingYinUtil;


/**
 * @author Administrator 基础数据-特维厂站信息
 */

@Named
@ViewScoped
public class SpecialMaintenanceStationController extends AbstractController {
    private static final long serialVersionUID = 5552779308770511020L;

    @Autowired
    private MaintenanceManager sm;
    @Autowired
    private MapDataCache cc;
    @Autowired
    private MaintenancePersistManager mpm;
    @Autowired
    private DepartManager dm;
    @Autowired
    private SubstationLedgerManager ledgerM;
    @Autowired
    private CimManager cimM;
    @Autowired
    private MaintenanceLogManager logM;
    @Autowired
    private EquipmentOverhualDetailManager overHualM;
    @Autowired
    private UserOperationManager  userOperationM;
    @Autowired
    private ManagementUnitMaintainManager managementUnitM;
    @Autowired
    private SuperDAO dao;
    @Autowired
    private SubstationLedgerManager slM;
    @Autowired
    private FaultSystemProperties pros;

    private final String SPECIAL_STATION_TEMPLATE = "SpecialTemplate.xlsx";
    private final String STATION_TEMPLATE = "StationTemplate.xlsx";

    private List<MaintenanceStation> specialStation = new ArrayList<MaintenanceStation>(); // 特维设备
    private List<MaintenanceStation> allSpecialStation;
    private List<MaintenanceStation> unBindStations = new ArrayList<MaintenanceStation>();
    private Map<String, List<String>> specialStationMap = new HashMap<>();
    private Map<String, List<MaintenanceStation>> rankMap = new HashMap<String, List<MaintenanceStation>>();
    private List<MaintenanceStationBreaker> specialBreaker;

    private TreeNode root = new DefaultTreeNode();
    private TreeNode currentSelect;
    private String filterStation;
    private String selectSid;
    private StreamedContent templateFile;

    private MaintenanceStation created = null;
    private MaintenanceStation selected = null;
    private int voltage = 500;
    private boolean clearAll = false;
    private int year;
    private String uploadYear;
    Map<Integer, List<Substation>> treeMap = new TreeMap<Integer, List<Substation>>();// 变电站map（电压等级-变电站）
    private TreeNode stationRoot;// 变电站tree
    private TreeNode[] selectedStation;// 选择的变电站
    private Set<Substation> selectedList = new HashSet<Substation>();// 已选择的变电站列表
    private String stationSearch;// 前台变电站查询

    private StreamedContent exportFile;
    private List<MaintenanceLog> maintenanceLogs;
    private List<String> maintenanceLogInfos;
    private boolean showAllColumns = false;
    private boolean overrideBreaker = false;
    private String content;
    private boolean createStatus = false;//新增为true  编辑为false
    private Boolean changeStationLedger= false;//判断是否根据改变的调管单位去维护变电站管理信息
    private MaintenanceStation preEdit = new MaintenanceStation();;
    private ManagementUnitDict choiceDepart ;//编辑更改调管单位时选择的调管单位
    private List<UserOperationLog>  auditLog;
    private Date logQueryStartDate;
    private Date logQueryEndDate;
    private String auditCreator; 
    private MaintenanceStation oldmS;
	private MaintenanceStation newmS;
	private boolean renderComparePanel;
	private Set<DataList> dataList = new HashSet<>();
	private Boolean queryCurrentDevice = false;
	
    @PostConstruct
    private void init() {
        allSpecialStation = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        uploadYear = String.valueOf(year);
        getAllowedStations();
        specialStationMap = initSpecialStationMap(allSpecialStation);
        rankMap = initRankMap();
        genLeftTree();
    }

    /**
     * 获取变电站权限
     */
    private void getAllowedStations() {
        allSpecialStation.clear();
        List<MaintenanceStation>  perS = sm.getDiffMaintenanceStationsByYearAndVoltage(year, voltage);;
        for (MaintenanceStation maintenanceStation : perS) {
            if(PermissionSecurityManager.hasOperationPermission(getCurrentUser().getCode(), maintenanceStation.getSubStationId())) {
                allSpecialStation.add(maintenanceStation);
            }
        }
    }

    private Map<String, List<String>> initSpecialStationMap(List<MaintenanceStation> allSpecialStation) {
        Map<String, List<String>> map = new HashMap<>();
        for (MaintenanceStation s : allSpecialStation) {
            String key = PingYinUtil.getPingYinHeader(s.getStation());
            List<String> ss = map.get(key);
            if (ss == null) {
                ss = new ArrayList<>();
                map.put(key, ss);
            }
            ss.add(s.getStation());
        }
        return map;
    }

    private Map<String, List<MaintenanceStation>> initRankMap() {
        Map<String, List<MaintenanceStation>> map = new HashMap<String, List<MaintenanceStation>>();
        for (MaintenanceStation s : allSpecialStation) {
            if (StringUtils.isNotEmpty(s.getTransMechanism())) {
                if (!map.containsKey(s.getTransMechanism())) {
                    map.put(s.getTransMechanism(), new ArrayList<MaintenanceStation>());
                }
                List<MaintenanceStation> stations = map.get(s.getTransMechanism());
                stations.add(s);
            } else {
            	 if (!map.containsKey("未设置调管单位")) {
            		 map.put("未设置调管单位", new ArrayList<MaintenanceStation>());
                 }
                List<MaintenanceStation> stations = map.get("未设置调管单位");
                stations.add(s);
            }
        }
        return map;
    }

    public void refresh() {
        filterStation = "";
        initTree();
    }

    public void initTree() {
        root = new DefaultTreeNode();
        getAllowedStations();
        rankMap = initRankMap();
        genLeftTree();
    }

    /**
     * 生成特维厂站树
     */
    private void genLeftTree() {
        root = new LibTreeNode("Root", null);
        // 组织机构的根节点，即南方电网
        List<DepartmentEntityBean> rootDepts = dm.findRootDepts();
        if (rootDepts.size() > 0) {
            DepartmentEntityBean rootDept = rootDepts.get(0);
            LibTreeNode rootNode = new LibTreeNode("root", rootDept, root);
            // 南方电网下一级部门节点
            List<DepartmentEntityBean> depts = dm.getDepartmentsByParent(rootDept.getId());
            for (DepartmentEntityBean dept : depts) {
                // 如果map中有该部门的名称，直接将该部门以及该部门下的特维厂站加入树中
                if (rankMap.containsKey(dept.getName())) {
                    TreeNode rankNode = new DefaultTreeNode("dept", dept, rootNode);
                    List<MaintenanceStation> stations = rankMap.get(dept.getName());
                    for (MaintenanceStation s : stations) {
                        new DefaultTreeNode("MaintenanceStation", s, rankNode);
                    }
                } else {
                    // 如果map中没有该部门的名称，则对其进行递归查找，看其子是否在map中有调度单位类型
                    recursionGetChildNode(dept, rootNode);
                }
            }
            /**
             * 如果特维厂站没有调管单位，也要在树中显示出来
             */
            if (rankMap.containsKey("未设置调管单位")) {
                TreeNode rankNode = new DefaultTreeNode("dept", "未设置调管单位", rootNode);
                List<MaintenanceStation> stations = rankMap.get("未设置调管单位");
                for (MaintenanceStation s : stations) {
                    new DefaultTreeNode("MaintenanceStation", s, rankNode);
                }
            }
            rootNode.setExpanded(true);
        }
    }

    /**
     * 递归查询子
     *
     * @param dept
     * @param treeNode
     */
    private void recursionGetChildNode(DepartmentEntityBean dept, TreeNode treeNode) {
        // 获取该部门的直接子部门
        List<DepartmentEntityBean> depts = dm.getDepartmentsByParent(dept.getId());
        // 如果map中有该部门的名称，直接将该部门以及父部门加入树中
        for (DepartmentEntityBean d : depts) {
            if (rankMap.containsKey(d.getName())) {
                TreeNode pNode = new DefaultTreeNode("dept", dept, treeNode);
                TreeNode rankNode = new DefaultTreeNode("dept", d, pNode);
                List<MaintenanceStation> stations = rankMap.get(d.getName());
                for (MaintenanceStation s : stations) {
                    new DefaultTreeNode("MaintenanceStation", s, rankNode);
                }
            } else {
                // 如果map中没有该部门的名称，则对其进行递归查找，看其子是否在map中有调度单位类型
                recursionGetChildNode(d, treeNode);
            }
        }
    }

    /**
     * 变电站tree，根据电压等级分组
     */
    private void genStationTreeByVoltage() {
        stationRoot = new DefaultTreeNode("Root", null);
        HashMap<String, Substation> stationMap = cc.getStationid_map();// 全部变电站
        //		Map<Integer, List<Substation>> treeMap = new TreeMap<Integer, List<Substation>>();//变电站map（电压等级-变电站）
        treeMap.clear();
        for (Map.Entry<String, Substation> entry : stationMap.entrySet()) {
            Substation subValue = entry.getValue();
            int voltage = (int) subValue.getStandVoltagelevel();
            List<Substation> subList = treeMap.get(voltage);
            if (null == subList) {
                subList = new ArrayList<Substation>();
                subList.add(subValue);
                treeMap.put(voltage, subList);
            } else {
                subList.add(subValue);
            }
        }
        for (Map.Entry<Integer, List<Substation>> entry : treeMap.entrySet()) {
            if (entry.getKey() != 0) {// 过滤掉0kV
                TreeNode treeNode = new DefaultTreeNode("voltage", entry.getKey() + "kV", stationRoot);// 外层节点
                List<Substation> subList = entry.getValue();
                for (Substation sub : subList) {
                    new DefaultTreeNode("substation", sub, treeNode);
                }
            }
        }
    }

    /**
     * 变电站设置前校验
     */
    public void preSettingSubstation() {
        stationSearch = null;
        genStationTreeByVoltage();// 变电站tree，根据电压等级分组（若一开始就初始化好，选择过节点，再次进入时，虽然后台清空selectedStation了，但前台展示有问题）
        selectedList.clear();
    }
    /**
     * @return
     */
    public boolean showPlanDate(MaintenanceStation ms) {
        if(ms.getChuandongTime()==null && StringUtils.isNotEmpty(ms.getPhaseALastFault())
                &&  StringUtils.isNotEmpty(ms.getPhaseBLastFault())
                &&  StringUtils.isNotEmpty(ms.getPhaseCLastFault())) {
            return true;
        }
        return false;
    }

    /**
     * 新增特维站点--变电站保存
     */
    public void substationSave() {
        List<String> stationIds = new ArrayList<String>();
        for (TreeNode node : selectedStation) {
        	Substation station = (Substation) node.getData();
            stationIds.add(station.getId());
        }
        for (Substation station : selectedList) {
        	 stationIds.add(station.getId());
		}
        try {
            mpm.generateMaintenanceByStations(getCurrentUser().getName(),year, stationIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        initTree();
        addSuccessMessage("保存成功");
    }

    /**
     * 保存前是否提示
     * @throws JsonProcessingException
     */
    public void preSubstationSave() throws JsonProcessingException {
        List<String> stationIds = new ArrayList<String>();
        List<String> jsons = new ArrayList<>();
        
        for (TreeNode node : selectedStation) {
        	 Substation station = (Substation) node.getData();
            stationIds.add(station.getId());
            ObjectMapper objMapper = new ObjectMapper();
            String jsonstr = objMapper.writeValueAsString(station);
            jsons.add(jsonstr);
        }
        for (Substation station : selectedList) {
        	 stationIds.add(station.getId());
             ObjectMapper objMapper = new ObjectMapper();
             String jsonstr = objMapper.writeValueAsString(station);
             jsons.add(jsonstr);
		}
        //如果存在数据，则需要提示
        if(exitMaintanceInformation(stationIds)) {
        	PrimeFaces.current().executeScript("PF('overrideConfirmDialog').show()");
        }else {
            substationSave();
            initTree();
        }

        createUserOperationLogByJsonListString(OperationType.BATCH_CREATE, jsons.toString());
    }

    private void createUserOperationLogByJsonListString(OperationType type, String jsons) {
        UserOperationLog uolog = new UserOperationLog();
        uolog.setOptype(type);
        uolog.setUserCode(getCurrentUser().getCode());
        uolog.setDept(getCurrentUser().getGroup().getName());
        uolog.setOperationDate(new Date());
        uolog.setFunctionName("特维厂站管理");
        uolog.setBeanType(ArrayList.class.getName());
        if("CREATE".equals(type.toString())||"BATCH_CREATE".equals(type.toString())) {
            uolog.setOldValue("");
            uolog.setNewValue(jsons);
        }else if("DELETE".equals(type.toString()) ||"BATCH_DELETE".equals(type.toString())) {
            uolog.setOldValue(jsons);
            uolog.setNewValue("");
        }
        userOperationM.create(uolog);

    }

    /**
     * 新增特维站点--判断添加的站点，是否存在已有特维信息的站点
     * 如果已有特维信息，则返回true
     * 如果没有特维信息，则返回false
     * @return
     */
    private boolean exitMaintanceInformation(List<String> stationIds) {
        for(String stationId:stationIds) {
            List<MaintenanceStation> maintationStations = sm.getMaintenanceStationsByStationIdAndYear(stationId, year);
            if(maintationStations.size()>0) {
                return true;
            }
        }
        return false;
    }




    /**
     * 根据变电站名称检索
     */
    public void searchBySubstation() {
        if (StringUtils.isNotEmpty(stationSearch) && !stationSearch.equals("全部")) {
            for (TreeNode tn : stationRoot.getChildren()) {
                tn.setExpanded(false);
                for (TreeNode trn : tn.getChildren()) {
                    Substation sub = (Substation) trn.getData();// dto
                    trn.setSelected(false);
                    if (stationSearch.equals(sub.getName())) {
                        selectedList.add(sub);
                        tn.setExpanded(true);
                        trn.setSelected(true);
                    }
                }
            }
        } else {
            genStationTreeByVoltage();
        }
    }

    /**
     * 重置
     */
    public void resetSubstation() {
        stationSearch = null;
        searchBySubstation();
    }

    public void autoCompleteStation(SelectEvent event) {
        Object item = event.getObject();
        if (null != item) {
            filterTree(item.toString());
        }
    }

    public List<String> completeSpStation(String query) {
        List<String> results = new ArrayList<String>();
        for (String s : specialStationMap.keySet()) {
            if (s.startsWith(query)) {
                results.addAll(specialStationMap.get(s));
            }
        }
        return results;
    }

    private void filterTree(String name) {
        Iterator<Entry<String, List<MaintenanceStation>>> iterator = rankMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, List<MaintenanceStation>> entry = iterator.next();
            String rank = entry.getKey();
            List<MaintenanceStation> stations = entry.getValue();
            for (MaintenanceStation s : stations) {
                if (s.getStation().equals(name)) {
                    root = new DefaultTreeNode();
                    List<DepartmentEntityBean> dept = dm.findDepartmentsByName(rank);
                    if (null != dept && dept.size() > 0) {
                        TreeNode rankNode = new DefaultTreeNode("dept", dept.get(0), root);
                        new DefaultTreeNode(MaintenanceStation.class.getSimpleName(), s, rankNode);
                        rankNode.setExpanded(true);
                    }
                    break;
                }
            }
        }
    }

    public void onNodeSelect(NodeSelectEvent event) {
        currentSelect = event.getTreeNode();
        specialStation.clear();
        if ("root".equals(currentSelect.getType())) {
            // 选中的是“南方电网”
            specialStation = sm.getMaintenanceStationsByYearAndVoltage(year, voltage);
        } else if ("dept".equals(currentSelect.getType())) {
            if ("String".equals(currentSelect.getData().getClass().getSimpleName())) {
                // 选中的是没有调管单位的
                specialStation = sm.getMaintenanceStationsByTransMechanism(null, year, voltage);
            } else {
                // 选中的是部门
                DepartmentEntityBean dept = (DepartmentEntityBean) currentSelect.getData();
                specialStation = getMaintenanceStations(dept);
            }
        } else if ("MaintenanceStation".equals(currentSelect.getType())) {
            // 选中的是变电站
            if ("String".equals(currentSelect.getParent().getData().getClass().getSimpleName())) {
                // 父部门是“未设置调管单位”
                selected=  (MaintenanceStation)currentSelect.getData();
                specialStation = sm.getMaintenanceStationsByStationNameAndYear(selected.getStation(),year);
            } else {
                selected = (MaintenanceStation) currentSelect.getData();
                DepartmentEntityBean dept = (DepartmentEntityBean) currentSelect.getParent().getData();
                MaintenanceStation sub = null;
                List<MaintenanceStation> stations = rankMap.get(dept.getName());
                for (MaintenanceStation station : stations) {
                    if (station.getStation().equals(selected.getStation())) {
                        selectSid = station.getSubStationId();
                        sub = station;
                        break;
                    }
                }
                if (null != selectSid) {
                    specialStation = sm.getMaintenanceStationsByStationIdAndYearAndVoltage(selectSid, year, voltage);
                } else if (null != sub) {
                    specialStation = sm.getMaintenanceStationsByStationName(sub.getStation());
                }
            }
        }
    }
    /**
     * 格式化计划事假能显示
     * @param item
     * @return
     */
    public String showPlanTime(MaintenanceStation item) {
        if (item.getChuandongTime() != null) {
            return DateUtil.getStringDate(item.getChuandongTime(), DateUtil.pattern_ymd);
        }else if (item.getChuandongTime() == null && (StringUtils.isNotEmpty(item.getPhaseALastFault()))
                && StringUtils.isNotEmpty(item.getPhaseBLastFault())
                && StringUtils.isNotEmpty(item.getPhaseCLastFault())) {
            return "---";
        }else if(item.getChuandongTime() == null && (StringUtils.isNotEmpty(item.getPhaseALastFault())
                || StringUtils.isNotEmpty(item.getPhaseBLastFault())
                || StringUtils.isNotEmpty(item.getPhaseCLastFault()))){
            return null;
        } else if((StringUtils.isEmpty(item.getPhaseALastFault())
                && StringUtils.isEmpty(item.getPhaseBLastFault())
                && StringUtils.isEmpty(item.getPhaseCLastFault()))){
            return null;
        }
        return null;
    }

    /**
     * 重新从数据库获取特维厂站table信息
     */
    private void refreshTable() {
        if (currentSelect != null) {
            specialStation.clear();
            if ("root".equals(currentSelect.getType())) {
                // 选中的是“南方电网”
                specialStation = sm.getMaintenanceStationsByYearAndVoltage(year, voltage);
            } else if ("dept".equals(currentSelect.getType())) {
                if ("String".equals(currentSelect.getData().getClass().getSimpleName())) {
                    // 选中的是没有调管单位的
                    specialStation = sm.getMaintenanceStationsByTransMechanism(null, year, voltage);
                } else {
                    // 选中的是部门
                    DepartmentEntityBean dept = (DepartmentEntityBean) currentSelect.getData();
                    specialStation = getMaintenanceStations(dept);
                }
            } else if ("MaintenanceStation".equals(currentSelect.getType())) {
                // 选中的是变电站
                if ("String".equals(currentSelect.getParent().getData().getClass().getSimpleName())) {
                    // 父部门是“未设置调管单位”
                    specialStation = sm.getMaintenanceStationsByStationName((String) currentSelect.getData());
                } else {
                    DepartmentEntityBean dept = (DepartmentEntityBean) currentSelect.getParent().getData();
                    MaintenanceStation sub = null;
                    List<MaintenanceStation> stations = rankMap.get(dept.getName());
                    for (MaintenanceStation station : stations) {
                        if (station.getStation().equals(((MaintenanceStation) currentSelect.getData()).getStation())) {
                            selectSid = station.getSubStationId();
                            sub = station;
                            break;
                        }
                    }
                    if (null != selectSid) {
                        specialStation = sm.getMaintenanceStationsByStationIdAndYearAndVoltage(selectSid, year,
                                voltage);
                    } else if (null != sub) {
                        specialStation = sm.getMaintenanceStationsByStationName(sub.getStation());
                    }
                }
            }
        }
    }

    private List<MaintenanceStation> getMaintenanceStations(DepartmentEntityBean dept) {
        // 当前部门下的特维设备
        List<MaintenanceStation> mStations = sm.getMaintenanceStationsByTransMechanism(dept.getName(), year, voltage);
        // 当前部门的子部门下的特维设备
        return recursionGetMaintenanceStation(dept, mStations);
    }

    private List<MaintenanceStation> recursionGetMaintenanceStation(DepartmentEntityBean dept,
                                                                    List<MaintenanceStation> mStations) {
        List<DepartmentEntityBean> depts = dm.findAllDepartMentByParent(dept.getId());
        for (DepartmentEntityBean d : depts) {
            List<MaintenanceStation> ms = sm.getMaintenanceStationsByTransMechanism(d.getName(), year, voltage);
            mStations.addAll(ms);
            recursionGetMaintenanceStation(d, mStations);
        }
        return mStations;
    }

    /**
     * 文件上传
     */
    public void handleFileUpload(FileUploadEvent event) {
        if (StringUtils.isEmpty(uploadYear)) {
            addErrorMessage("请选择维护设备年份");
            return;
        }
        try {
            List<List<Object>> res = ExcelUtil.readExcel(event.getFile().getInputstream(), 0);
            if (res.get(0).size() < 14) {
                addErrorMessage("文件格式不正确，请先下载模板！");
                return;
            }
            if (res.size() == 1) {
                addErrorMessage("文件内容为空，请检测上传的文件！"+event.getFile().getFileName());
                return;
            }
            Boolean isclear = Boolean.valueOf(event.getComponent().getAttributes().get("isclear").toString());
            List<String> uploads = sm.uploadMaintenanceDate(Integer.valueOf(uploadYear), res.subList(1, res.size()), voltage,isclear);
            updateSpecialStationId();
            rankMap = initRankMap();
            initTree();
            addSuccessMessage("文件更新成功");
            createUserOperationLogByJsonListString(OperationType.BATCH_CREATE, uploads.toString());
        } catch (IOException e) {
            e.printStackTrace();
            addErrorMessage("文件解析失败，请先下载模板！");
        } catch (Exception e) {
            e.printStackTrace();
            addErrorMessage("文件解析失败，请先下载模板！");
        }
    }

    public void handleStationFile(FileUploadEvent event) {
        List<String> stationIds = new ArrayList<String>();
        List<String> jsons = new ArrayList<>();
        if (StringUtils.isEmpty(uploadYear)) {
            addErrorMessage("请选择维护设备年份");
            return;
        }
        try {
            List<List<Object>> res = ExcelUtil.readExcel(event.getFile().getInputstream(), 1);
			/*if (res.get(0).size() >1) {
				addErrorMessage("文件格式不正确，请先下载模板！");
				return;
			}*/
            int i = 0;
            List<Integer> errorList = new ArrayList<Integer>();
            for (List<Object> list : res) {
                i++;
                String stationName = (String) list.get(0);
                Substation station = cimM.getSubstationByName(stationName, null);
                if (null != station) {
                    stationIds.add(station.getId());
                    ObjectMapper objMapper = new ObjectMapper();
                    String jsonstr = objMapper.writeValueAsString(station);
                    jsons.add(jsonstr);
                } else {
                    // 未能根据名称找到对应的变电站
                    errorList.add(i);
                }
            }
            int tempYear = Integer.parseInt(uploadYear);
            mpm.generateMaintenanceByStations(getCurrentUser().getName(),tempYear, stationIds);
            if (errorList.size() > 0) {
                StringBuffer alertMsg = new StringBuffer();
                alertMsg.append("上传文件中，第");
                for (Integer index : errorList) {
                    alertMsg.append(index + "、");
                }
                alertMsg.append("行变电站名称有误，请核对后重新上传");
                addErrorMessage(alertMsg + "");
            }
            updateSpecialStationId();
            rankMap = initRankMap();
            initTree();
            createUserOperationLogByJsonListString(OperationType.BATCH_CREATE, jsons.toString());
            addSuccessMessage("变电站上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            addErrorMessage("文件解析失败，请先下载模板！");
        } catch (Exception e) {
            e.printStackTrace();
            addErrorMessage("文件解析失败，请先下载模板！");
        }
    }

    /**
     * 更新缓存中的特维
     */
    private void updateSpecialStationId() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        // 更新当前年份的specialStationId
        if (Integer.valueOf(uploadYear) == calendar.get(Calendar.YEAR)) {
            cc.getSpecialStationId().clear();
            cc.genSpecialStationId();
        }
    }

    /**
     * 文件下载
     */
    public void fileDownloadView() {
        InputStream stream;
        try {
            stream = new FileInputStream(new File(pros.getTempletePath() + SPECIAL_STATION_TEMPLATE));
            templateFile = new DefaultStreamedContent(stream, "xlsx", SPECIAL_STATION_TEMPLATE);
        } catch (FileNotFoundException e) {
            addErrorMessage("文件不存在");
            e.printStackTrace();
        }
    }

    /**
     * 变电站模板下载
     */
    public void downLoadStationTemplate() {
        InputStream input;
        try {
            input = new FileInputStream(new File(pros.getTempletePath() + STATION_TEMPLATE));
            templateFile = new DefaultStreamedContent(input, "xlsx", STATION_TEMPLATE);
        } catch (FileNotFoundException e) {
            addErrorMessage("文件不存在");
            e.printStackTrace();
        }
    }

    /**
     * 所有未绑定设备的纪录
     */
    public void unBind() {
        unBindStations = sm.getUnBindStations(year);
    }

    public void getBreakerByPid() {
		preEdit = new MaintenanceStation();;
		createStatus = false;
		changeStationLedger = false;
		specialBreaker = sm.getBreakersByBayName(selected.getId(),selected.getBlankName());
		try {
			BeanUtils.copyBean(selected,preEdit);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    public void createNewDevice() {
        createStatus = true;
        created = new MaintenanceStation();
        created.setCompanyName(selected.getCompanyName());
        created.setStation(selected.getStation());
        created.setSubStationId(selected.getSubStationId());
        created.setTransMechanism(selected.getTransMechanism());
        created.setOperationDepartment(selected.getOperationDepartment());
    }

    public void saveNewDevice() throws Exception {
        created.setYear(year);
        created.setVoltage(voltage);
        created.setCreator(getCurrentUser().getName());
        if (!StringUtils.isEmpty(created.getBlankId())) { // 选择某个间隔后单独保存，否则保存该站下所有间隔
            created = sm.saveMainStation(created, Integer.valueOf(year), created.getBlankName(), voltage);
            mpm.updateMaintenance(created);
            cc.getSpecialStationId().add(created.getId());
        }
        sm.createMainStationsOrBreakers(created, uploadYear);
        getAllowedStations();
        specialStation = sm.getMaintenanceStationsByStationIdAndYearAndVoltage(selectSid, year, voltage);
        rankMap = initRankMap();
        createUserOperationLog(OperationType.CREATE,null,created);
        initTree();
        addSuccessMessage("保存成功");
    }


    /**
     *创建操作审计日志
     * @param mStation
     * @param selected2
     * @param create
     * @throws JsonProcessingException
     */
    private void createUserOperationLog(OperationType type, MaintenanceStation oldValue, MaintenanceStation newValue) throws JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        UserOperationLog uolog = new UserOperationLog();
        uolog.setOptype(type);
        uolog.setUserCode(getCurrentUser().getCode());
        uolog.setDept(getCurrentUser().getGroup().getName());
        uolog.setOperationDate(new Date());
        uolog.setFunctionName("特维厂站管理");
        uolog.setBeanType(MaintenanceStation.class.getName());
        if("CREATE".equals(type.toString())) {
            String jsonstr = objMapper.writeValueAsString(newValue);
            uolog.setOldValue("");
            uolog.setNewValue(jsonstr);
        }else if("UPDATE".equals(type.toString())) {
            String jsonstr = objMapper.writeValueAsString(oldValue);
            ObjectMapper objMapper2 = new ObjectMapper();
            String jsonstr2 = objMapper2.writeValueAsString(newValue);
            uolog.setOldValue(jsonstr);
            uolog.setNewValue(jsonstr2);
        }else if("DELETE".equals(type.toString())) {
            String jsonstr = objMapper.writeValueAsString(oldValue);
            uolog.setOldValue(jsonstr);
            uolog.setNewValue("");
        }
        userOperationM.create(uolog);
    }

    public void deleteDevice() throws JsonProcessingException {
        for (MaintenanceStation device : specialStation) {
            if (selected.getId().equals(device.getId())) {
                specialStation.remove(device);
                allSpecialStation.remove(device);
                cc.getSpecialStationId().remove(device.getId());
                sm.deleteMaintenanceStation(selected.getId());
                createUserOperationLog(OperationType.DELETE, selected,null);
                selected = null;
                addSuccessMessage("删除成功");
                break;
            }
        }
        currentSelect = null;
        initTree();
    }

    public void update() {
        if (selected != null) {
            try {
                selected.setCreator(getCurrentUser().getName());
                if(selected.getFinishedTime()==null) {
                    selected.setPhaseALastFault(null);
                    selected.setPhaseBLastFault(null);
                    selected.setPhaseCLastFault(null);
                }
                mpm.updateMaintenance(selected);
                updateHistoryAndStationMessage(selected);
                createUserOperationLog(OperationType.UPDATE, preEdit,selected);
                addSuccessMessage("保存成功");
            } catch (Exception e) {
                e.printStackTrace();
                addErrorMessage("保存失败");
            }
            initTree();
            selected = null;
            //sm.saveMaintenanceStation(selected);
        }
        //		if (specialBreaker != null) {
        //			for (MaintenanceStationBreaker breaker : specialBreaker) {
        //				sm.saveBreaks(breaker);
        //			}
        //		}
        //		if (null != selectSid) {
        //			specialStation = sm.getMaintenanceStationsByStationIdAndYearAndVoltage(selectSid, year, voltage);
        //		} else {
        //			specialStation = sm.getMaintenanceStationsByStationName((String) currentSelect.getData());
        //		}

    }


    /**
     * 根据修改的单位信息 选择更新历史信息/维护变电站信息
     * @param selected2
     */
    private void updateHistoryAndStationMessage(MaintenanceStation mStation) {
        if(changeStationLedger) {
            changeStationLedger(mStation);
        }
    }

    /**
     * 维护变电站管理单位信息
     * @param mStation
     */
    private void changeStationLedger(MaintenanceStation mStation) {
        if(mStation.getSubStationId()!=null) {
            updateSubstationLedger(mStation);
            updatePrimaryLedger(mStation);
        }else {
            addErrorMessage("此变电站未被维护，请联系管理员");
        }
    }

    private void updatePrimaryLedger(MaintenanceStation mStation) {
        List<PrimaryEquipmentLedger>  pets = dao.findByCondition(PrimaryEquipmentLedger.class, "equipmentType = '变电站'  and cimId = ?1", mStation.getSubStationId());
        if(pets.size()==1) {
            PrimaryEquipmentLedger change = pets.get(0);
            change.setDispatchUnit(mStation.getTransMechanism());
            change.setDispatchUnitId(choiceDepart.getId());
            managementUnitM.createOrUpdate(change);

        }else {
            addErrorMessage("此变电站信息出现错误，请联系管理员");
        }

    }

    private void updateSubstationLedger(MaintenanceStation mStation) {
        SubstationLedger  sl = slM.findSubstationLedger(mStation.getSubStationId());
        if(sl!=null) {
            sl.setDispatchUnit(mStation.getTransMechanism());
            sl.setDispatchUnitId(choiceDepart.getId());
            dao.createOrUpdate(sl, SubstationLedger.class);
        }
    }

    // 模拟通道关联设备
    public void getEquipmentByStation() {
        Map<String, Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", false);
        options.put("width", 600);
        options.put("height", 400);
        Map<String, List<String>> params = new HashMap<>();
        List<String> s = new ArrayList<>();
        s.add(selected.getSubStationId());
        params.put("stationId", s);
        openDialog("/ui/common/equipment_selector_single", params, options);
    }

    public void selectEquipmentByStation() {
        Map<String, Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", false);
        options.put("width", 600);
        options.put("height", 400);
        Map<String, List<String>> params = new HashMap<>();
        List<String> s = new ArrayList<>();
        s.add(sm.findStationByName(created.getStation()));
        params.put("stationId", s);
        openDialog("/ui/common/equipment_selector_single", params, options);
    }

    public void onAnologSelectorChosen(SelectEvent event) {
        if (event.getObject() instanceof IdentifiedObject) {
            IdentifiedObject equipment = (IdentifiedObject) event.getObject();
            selected.setBlankName(equipment.getName());
            if (equipment instanceof LineSegment) {
                selected.setEquipmentType("线路");
            } else if (equipment instanceof BusbarSection) {
                selected.setEquipmentType("母线");
            } else if (equipment instanceof PowerTransformer) {
                selected.setEquipmentType("变压器");
            } else {
                selected.setEquipmentType("其他");
            }
            selected.setBlankId(equipment.getId());
            selected.setBlankName(equipment.getName());
            if(equipment  instanceof BusbarSection){
                BusbarSection bar = (BusbarSection) equipment;
                if(StringUtils.isNotBlank(bar.getAliasName())&&bar.getAliasName().contains("滤波器")) {
                    selected.setBlankName(bar.getAliasName());
                }
            }
            // 1.删除旧breaker
            sm.deletBreakerByPid(selected.getId());
            // 2.更新新的breaker
            sm.generateStationBreakers(selected, uploadYear);
            getBreakerByPid();
        }
    }

    public void onGetEquipment(SelectEvent event) {
        if (event.getObject() instanceof IdentifiedObject) {
            IdentifiedObject equipment = (IdentifiedObject) event.getObject();
            created.setBlankName(equipment.getName());
            created.setBlankId(equipment.getId());
            if(equipment  instanceof BusbarSection){
                BusbarSection bar = (BusbarSection) equipment;
                if(StringUtils.isNotBlank(bar.getAliasName())&&bar.getAliasName().contains("滤波器")) {
                    created.setBlankName(bar.getAliasName());
                }
            }
        }
    }

    public void rowSelection(SelectEvent event) {
        selected = (MaintenanceStation) event.getObject();
    }

    public void changeYear() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map<String, String> map = context.getExternalContext().getRequestParameterMap();
        String year = map.get("year").toString();
        this.year = Integer.valueOf(year);
        uploadYear = year;
        initTree();
        specialStationMap = initSpecialStationMap(allSpecialStation);
        filterStation = "";
        specialStation.clear();
    }

    /**
     * 该方法不可删除，用于选择上传电压的ajax提交
     */
    public void updateVoltage() {
        //System.out.println(voltage);
    	//log.info(voltage);
    }

    public void updateYear() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map<String, String> map = context.getExternalContext().getRequestParameterMap();
        uploadYear = map.get("year").toString();
    }

    /**
     * 选择变电站后
     *
     * @param event
     */
    public void onSubstationChosen(SelectEvent event) {
        Substation subStation = (Substation) event.getObject();
        SubstationLedger stationLedger = ledgerM.findSubstationLedger(subStation.getId());
        // 运维单位
        DepartmentEntityBean dept = null;
        if (null != stationLedger) {
            if (StringUtils.isNotEmpty(stationLedger.getMaintenanceUnitId())) {
                dept = dm.findDepartmentById(stationLedger.getMaintenanceUnitId());
            } else if (StringUtils.isNotEmpty(stationLedger.getMaintenanceUnit())) {
                List<DepartmentEntityBean> list = dm.findDepartmentsByName(stationLedger.getMaintenanceUnit());
                if (list.size() > 0) {
                    dept = list.get(0);
                }
            }
        }
        // 运维分子公司
        DepartmentEntityBean company = null;
        if (null != dept) {
            company = getCompanyNameByMaintenanceUnit(dept);
        }
        if (null == selected||createStatus==true) {
            // 新增
            created.setStation(subStation.getName());
            created.setSubStationId(subStation.getId());
            if (null != stationLedger) {
                created.setTransMechanism(stationLedger.getDispatchUnit());
                created.setOperationDepartment(stationLedger.getMaintenanceUnit());
                if (null != company) {
                    created.setCompanyName(company.getName());
                }
            } else {
                created.setTransMechanism(null);
                created.setOperationDepartment(null);
                created.setCompanyName(null);
            }
        } else {
            // 编辑
            selected.setStation(subStation.getName());
            selected.setSubStationId(subStation.getId());
            if (null != stationLedger) {
                selected.setTransMechanism(stationLedger.getDispatchUnit());
                selected.setOperationDepartment(stationLedger.getMaintenanceUnit());
                if (null != company) {
                    selected.setCompanyName(company.getName());
                    selected.setStation(company.getName());
                }
            } else {
                selected.setTransMechanism(null);
                selected.setOperationDepartment(null);
                selected.setCompanyName(null);
                selected.setStation(null);
            }
        }
    }

    /**
     * 根据运维单位获得运维分子公司
     *
     * @param dept
     * @return
     */
    private DepartmentEntityBean getCompanyNameByMaintenanceUnit(DepartmentEntityBean dept) {
        // 递归获取指定部门的所有上级部门，按照层级降序排序
        DepartmentEntityBean result = null;
        if (null != dept) {
            List<DepartmentEntityBean> pDepts = dm.recursiveFindParentDepartments(dept);
            if (pDepts.size() > 1) {
                result = pDepts.get(1);
            } else if (pDepts.size() > 0) {
                result = pDepts.get(0);
            }
        }
        return result;
    }

    /**
     * 选择调管单位后
     *
     * @param event
     */
    public void onDispatchUnitChosen(SelectEvent event) {
        ManagementUnitDict depart = (ManagementUnitDict) event.getObject();
        choiceDepart = depart;
        if (null == selected||createStatus==true) {
            created.setTransMechanism(depart.getName());
        } else {
            selected.setTransMechanism(depart.getName());
        }

    }

    /**
     * 选择运维单位后
     *
     * @param event
     */
    public void onMaintenanceUnitChosen(SelectEvent event) {
        ManagementUnitDict depart = (ManagementUnitDict) event.getObject();
        if (null == selected||createStatus==true) {
            created.setOperationDepartment(depart.getName());
        } else {
            selected.setOperationDepartment(depart.getName());
        }
    }

    /**
     * 选择运维分子公司后
     *
     * @param event
     */
    public void onCompanyChosen(SelectEvent event) {
        ManagementUnitDict depart = (ManagementUnitDict) event.getObject();
        if (null == selected ||createStatus==true) {
            created.setCompanyName(depart.getName());
        } else {
            selected.setCompanyName(depart.getName());
        }
    }

    /**
     * 导出特维设备
     */
    public void exportRecords() {
        sm.exportSpecialMaintenanceStation(specialStation);
        String exportDir = pros.getDownloadTmPath();
        String fileName = year + "-" + voltage + "kV MaintenanceStation.xlsx";
        InputStream stream;
        try {
            stream = new FileInputStream(new File(exportDir + fileName));
            exportFile = new DefaultStreamedContent(stream, exportDir, fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void showMaintenanceLog(MaintenanceStation maintenanceStation) {
        if (maintenanceLogInfos != null) {
            maintenanceLogInfos.clear();
        } else {
            maintenanceLogInfos = new ArrayList<String>();
        }
        List<MaintenanceLog> temp = logM.findMaintenanceLogByDeviceIdStationIdTypeAndYear(
                maintenanceStation.getBlankId(), maintenanceStation.getSubStationId(), "chuandong",
                maintenanceStation.getYear());
        for (MaintenanceLog m : temp) {
            String log = m.getInfo();
            maintenanceLogInfos.add(log);
        }

        analysisProcedure(maintenanceStation);
    }

    public void updateMaintenanceEquLastFault() {
        try {
            mpm.updateMaintenance(selected);
            refreshTable();
            addSuccessMessage("更新成功");
        } catch (Exception e) {
            addErrorMessage("重新生成特维信息失败");
        }
    }

    public void preUpdateEquipment(MaintenanceStation device) {
        selected = device;
        PrimeFaces.current().executeScript("PF('confirmDialog').show()");
    }

    public void analysisProcedure(MaintenanceStation station) {
        content="";
        if(StringUtils.isBlank(station.getOverhaulId())) {
            content = "无关联的检修票记录";
            return;
        }
        EquipmentOverhaulDetail overhaulDetail = overHualM.getEquipmentOverhaulDetailById(station.getOverhaulId());
        if(overhaulDetail==null) {
            content = "检修票无详细记录";
            return;
        }
        content = overhaulDetail.getOverhaulContent();//根据特维一条数据得到检修票id 查到内容
        if(StringUtils.isBlank(content)) {
            content = "检修票无详细记录";
        }
    }

    public void deleteBySubstation() throws JsonProcessingException {
        List<String> jsons = new ArrayList<>();
        if (selected != null) {
            List<MaintenanceStation> removeDevices = new ArrayList<>();
            if(selected.getSubStationId()!=null) {
                removeDevices = sm.getMaintenanceStationsByStationIdAndYear(selected.getSubStationId(), year);
            }else {
                removeDevices = sm.getMaintenanceStationsByStationNameAndYearAndVoltage(selected.getStation(), year, selected.getVoltage());
            }
            for (MaintenanceStation device : removeDevices) {
                ObjectMapper objMapper = new ObjectMapper();
                String jsonString = objMapper.writeValueAsString(device);
                jsons.add(jsonString);
                deleteByDevice(device);
            }
        }
        createUserOperationLogByJsonListString(OperationType.BATCH_DELETE, jsons.toString());
        selected =  null;
        initTree();
        addSuccessMessage("删除成功");
    }

    /**
     * 根据
     * @param device
     */
    private void deleteByDevice(MaintenanceStation device) {
        specialStation.remove(device);
        allSpecialStation.remove(device);
        cc.getSpecialStationId().remove(device.getId());
        sm.deleteMaintenanceStation(device.getId());
    }

    /**
     * 日志记录
     */
    public void initAuditLog() {
    	queryCurrentDevice = true;
        auditLog = dao.findAll(UserOperationLog.class);
        queryCurrentDevice();
       

    }

    private void comparatorReversed() {
    	 Comparator<UserOperationLog> comparator =
                 (t1, t2) -> t1.getOperationDate().compareTo(t2.getOperationDate());
         auditLog.sort(comparator.reversed());		
	}

	/**
     * 根据条件查询日志记录
     */
    public void queryAuditLogByCondition() {
        String whereCause = " 1 = 1  ";
        List<Object> args = new ArrayList<>();
        if(logQueryStartDate != null) {
            whereCause += " and  operationDate >= ?" ;
            args.add(logQueryStartDate);
        }
        if(logQueryEndDate != null) {
            whereCause += " and  operationDate <= ?" ;
            String end = DateUtil.getStringDate(logQueryEndDate, DateUtil.pattern_ymd) + " 23:59:59";
            Date endvalue =DateUtil.getDateByString(end, DateUtil.pattern_ymdhms);
            args.add(endvalue);
        }
        auditLog = dao.findByCondition(UserOperationLog.class, whereCause, args.toArray());
        queryCurrentDevice();
    }
    
    /***
     * 当前选中间隔的日志
     */
    private void queryCurrentDevice() {
    	if(queryCurrentDevice) {//根据当前选中的间隔过滤对应日志
    		if(selected==null) {
        		addErrorMessage("请先选择要查看的设备");
        		return;
        	}
    		List<UserOperationLog> logs = new ArrayList<>();
    		for (UserOperationLog log : auditLog) {
				if(StringUtils.isNotBlank(log.getOldValue())&&log.getOldValue().contains(selected.getBlankName())
						&&log.getOldValue().contains(selected.getStation())) {
					logs.add(log);
				}else if(StringUtils.isNotBlank(log.getNewValue())&&log.getNewValue().contains(selected.getBlankName())
						&&log.getNewValue().contains(selected.getStation())) {
					logs.add(log);
				}
			}
    		auditLog.clear();
    		auditLog = logs;
    		comparatorReversed();
    	}
    }
    
    
    
    /**
     * 重置日志记录
     */
    public void resetAuditLog() {
        logQueryStartDate = null;
        logQueryEndDate = null;
        queryCurrentDevice = false;
        queryAuditLogByCondition();

    }

    
    /**
	 * 值对比
	 * @param ms
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public void valueCompare(UserOperationLog log) throws Exception {
		dataList.clear();
		oldmS = new MaintenanceStation();
		newmS = new MaintenanceStation();
		renderComparePanelCharge(log);
		if(renderComparePanel) { //true  间隔显示面板   false 厂站名显示面板
			if(StringUtils.isNotBlank(log.getOldValue())) {
				ObjectMapper objectMapper = new ObjectMapper();
				oldmS = objectMapper.readValue(log.getOldValue(), MaintenanceStation.class);
			}
			if(StringUtils.isNotBlank(log.getNewValue())) {
				ObjectMapper objectMapper = new ObjectMapper();
				newmS = objectMapper.readValue(log.getNewValue(), MaintenanceStation.class);
			}
		}else {//批量删除 列出来间隔名   删除 列对象
			getDataList(log, log.getOptype());
		}
	}
	private void getDataList(UserOperationLog log, OperationType batchDelete) throws Exception {
		// TODO Auto-generated method stub
		Set<String>  name = new HashSet<>();
		if(batchDelete.equals(OperationType.BATCH_DELETE)) {
			if(StringUtils.isNotBlank(log.getOldValue())) {
				ObjectMapper objectMapper = new ObjectMapper();
				List<MaintenanceStation> msList = objectMapper.readValue(log.getOldValue(), new TypeReference<List<MaintenanceStation>>() {});
				DataList data = new DataList();
				data.setName(msList.get(0).getStation());
				dataList.add(data);
			}
		}else if(batchDelete.equals(OperationType.BATCH_CREATE)) {
			if(StringUtils.isNotBlank(log.getNewValue())) {
				ObjectMapper objectMapper = new ObjectMapper();
				List<Substation> msList = objectMapper.readValue(log.getNewValue(), new TypeReference<List<Substation>>() {});
			     for (Substation substation : msList) {
			    	 name.add(substation.getName());
				}
			}
		}
		for (String string : name) {
			     DataList data = new DataList();
				data.setName(string);
				dataList.add(data);
		}
	}
	
	/**
	 * 根据操作类型判断页面显示什么样的效果
	 * @param log
	 */
	private void renderComparePanelCharge(UserOperationLog log) {
		// TODO Auto-generated method stub
		if(log.getOptype().toString().equals(OperationType.UPDATE.toString())
				||log.getOptype().toString().equals(OperationType.CREATE.toString())
				||log.getOptype().toString().equals(OperationType.DELETE.toString())) {
			renderComparePanel = true;
		}else  {
			renderComparePanel = false ;
		}
	}

	/**
	 * 获取操作类型
	 * @param type
	 */
	public String getOperateType(String type) {
		String operateType = "";
		if(type.equals(OperationType.UPDATE.toString())) {
			operateType = "编辑";
		}else if(type.equals(OperationType.DELETE.toString())) {
			operateType = "删除";
		}else if(type.equals(OperationType.CREATE.toString())) {
			operateType = "新增间隔";
		}else if(type.equals(OperationType.BATCH_CREATE.toString())) {
			operateType = "新增特维厂站（上传特维设备）";
		}else if(type.equals(OperationType.BATCH_DELETE.toString())) {
			operateType = "删除特维厂站";
		}else if(type.equals(OperationType.BATCH_UPDATE.toString())) {//暂时没有 
			operateType = "批量更新";
		}
		return operateType;
	}
	
	
	 public class DataList{
	    	
	    	private String name;

			public String getName() {
				return name;
			}

			public void setName(String name) {
				this.name = name;
			}
	    	
	    }
    public class maintenanceLogInfo {
        private String phase;
        private String faultType;
        private String time;

        public String getPhase() {
            return phase;
        }

        public void setPhase(String phase) {
            this.phase = phase;
        }

        public String getFaultType() {
            return faultType;
        }

        public void setFaultType(String faultType) {
            this.faultType = faultType;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }
    }

    public List<MaintenanceStation> getSpecialStation() {
        return specialStation;
    }

    public void setSpecialStation(List<MaintenanceStation> specialStation) {
        this.specialStation = specialStation;
    }

    public List<MaintenanceStationBreaker> getSpecialBreaker() {
        return specialBreaker;
    }

    public void setSpecialBreaker(List<MaintenanceStationBreaker> specialBreaker) {
        this.specialBreaker = specialBreaker;
    }

    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public TreeNode getCurrentSelect() {
        return currentSelect;
    }

    public void setCurrentSelect(TreeNode currentSelect) {
        this.currentSelect = currentSelect;
    }

    public String getFilterStation() {
        return filterStation;
    }

    public void setFilterStation(String filterStation) {
        this.filterStation = filterStation;
    }

    public MaintenanceStation getCreated() {
        return created;
    }

    public void setCreated(MaintenanceStation created) {
        this.created = created;
    }

    public MaintenanceStation getSelected() {
        return selected;
    }

    public void setSelected(MaintenanceStation selected) {
        this.selected = selected;
    }

    public List<MaintenanceStation> getAllSpecialStation() {
        return allSpecialStation;
    }

    public void setAllSpecialStation(List<MaintenanceStation> allSpecialStation) {
        this.allSpecialStation = allSpecialStation;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public StreamedContent getTemplateFile() {
        return templateFile;
    }

    public String getUploadYear() {
        return uploadYear;
    }

    public void setUploadYear(String uploadYear) {
        this.uploadYear = uploadYear;
    }

    public List<MaintenanceStation> getUnBindStations() {
        return unBindStations;
    }

    public void setUnBindStations(List<MaintenanceStation> unBindStations) {
        this.unBindStations = unBindStations;
    }

    public int getVoltage() {
        return voltage;
    }

    public void setVoltage(int voltage) {
        this.voltage = voltage;
    }

    public TreeNode getStationRoot() {
        return stationRoot;
    }

    public void setStationRoot(TreeNode stationRoot) {
        this.stationRoot = stationRoot;
    }

    public TreeNode[] getSelectedStation() {
        return selectedStation;
    }

    public void setSelectedStation(TreeNode[] selectedStation) {
        this.selectedStation = selectedStation;
    }

    public Set<Substation> getSelectedList() {
        return selectedList;
    }

    public void setSelectedList(Set<Substation> selectedList) {
        this.selectedList = selectedList;
    }

    public String getStationSearch() {
        return stationSearch;
    }

    public void setStationSearch(String stationSearch) {
        this.stationSearch = stationSearch;
    }

    public StreamedContent getExportFile() {
        return exportFile;
    }

    public void setExportFile(StreamedContent exportFile) {
        this.exportFile = exportFile;
    }

    public List<MaintenanceLog> getMaintenanceLogs() {
        return maintenanceLogs;
    }

    public void setMaintenanceLogs(List<MaintenanceLog> maintenanceLogs) {
        this.maintenanceLogs = maintenanceLogs;
    }

    public List<String> getMaintenanceLogInfos() {
        return maintenanceLogInfos;
    }

    public void setMaintenanceLogInfos(List<String> maintenanceLogInfos) {
        this.maintenanceLogInfos = maintenanceLogInfos;
    }

    public boolean isShowAllColumns() {
        return showAllColumns;
    }

    public void setShowAllColumns(boolean showAllColumns) {
        this.showAllColumns = showAllColumns;
    }

    public boolean isOverrideBreaker() {
        return overrideBreaker;
    }

    public Set<DataList> getDataList() {
		return dataList;
	}

	public void setDataList(Set<DataList> dataList) {
		this.dataList = dataList;
	}

	public void setOverrideBreaker(boolean overrideBreaker) {
        this.overrideBreaker = overrideBreaker;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public boolean isCreateStatus() {
        return createStatus;
    }

    public void setCreateStatus(boolean createStatus) {
        this.createStatus = createStatus;
    }

    public boolean isClearAll() {
        return clearAll;
    }

    public void setClearAll(boolean clearAll) {
        this.clearAll = clearAll;
    }


    public boolean isChangeStationLedger() {
        return changeStationLedger;
    }

    public void setChangeStationLedger(boolean changeStationLedger) {
        this.changeStationLedger = changeStationLedger;
    }

    public List<UserOperationLog> getAuditLog() {
        return auditLog;
    }

    public Boolean getQueryCurrentDevice() {
		return queryCurrentDevice;
	}

	public void setQueryCurrentDevice(Boolean queryCurrentDevice) {
		this.queryCurrentDevice = queryCurrentDevice;
	}

	public void setAuditLog(List<UserOperationLog> auditLog) {
        this.auditLog = auditLog;
    }

    public Date getLogQueryStartDate() {
        return logQueryStartDate;
    }

    public void setLogQueryStartDate(Date logQueryStartDate) {
        this.logQueryStartDate = logQueryStartDate;
    }

    public Date getLogQueryEndDate() {
        return logQueryEndDate;
    }

    public void setLogQueryEndDate(Date logQueryEndDate) {
        this.logQueryEndDate = logQueryEndDate;
    }

    public String getAuditCreator() {
        return auditCreator;
    }

    public void setAuditCreator(String auditCreator) {
        this.auditCreator = auditCreator;
    }

	public MaintenanceStation getOldmS() {
		return oldmS;
	}

	public void setOldmS(MaintenanceStation oldmS) {
		this.oldmS = oldmS;
	}

	public MaintenanceStation getNewmS() {
		return newmS;
	}

	public void setNewmS(MaintenanceStation newmS) {
		this.newmS = newmS;
	}

	public boolean isRenderComparePanel() {
		return renderComparePanel;
	}

	public void setRenderComparePanel(boolean renderComparePanel) {
		this.renderComparePanel = renderComparePanel;
	}

	public Map<String, List<String>> getSpecialStationMap() {
		return specialStationMap;
	}

	public void setSpecialStationMap(Map<String, List<String>> specialStationMap) {
		this.specialStationMap = specialStationMap;
	}



}
